// utils/v-scroll.ts
import PerfectScrollbar from "perfect-scrollbar";
import "perfect-scrollbar/css/perfect-scrollbar.css";
import type { App } from "vue";

interface IuseScroll {
  (el: HTMLElement, cb: (e: any) => void): void;
  install: (app: App, name: string) => void;
}

export const useScroll: IuseScroll =  (
  el: HTMLElement,
  callback: (e: any) => void
) => {
  if ((el as any)._ps_ instanceof PerfectScrollbar) {
    (el as any)._ps_.update();
    return;
  }
  const ps = new PerfectScrollbar(el, {
    wheelSpeed: 1,
    wheelPropagation: true,
    minScrollbarLength: 20,
  });
  callback(ps);
  (el as any)._ps_ = ps;
};

const install = (app: App, directiveName = "scroll") => {
  app.directive(directiveName, {
    mounted(el: HTMLElement, binding: any) {
      const callback = binding.value || ((e: any) => e);
      useScroll(el, callback);
    },
    updated(el: HTMLElement, binding: any) {
      const callback = binding.value || ((e: any) => e);
      useScroll(el, callback);
    },
    unmounted(el: HTMLElement) {
      (el as any)._ps_.destroy();
      (el as any) = null;
    },
  });
};

useScroll.install = install;

// vue 插件接收一个 install 函数
// 用法： app.use(useScroll)
export default useScroll;
